<?php


namespace App\Http\Controllers;

use App\Facades\Tx;
use App\Models\MoneyRecord;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function user(Request $request)
    {
        return Tx::success($request->user());
    }

    //完善支付宝账号
    public function updateAlipay(Request $request)
    {
        return Tx::success(User::where('id',\Auth::id())->update(
            [
                'real_name' => $request->get('real_name'),
                'alipay_account' => $request->get('alipay_account')
            ]
        ));
    }

    //提现
    public function withdraw(Request $request)
    {
        $this->validate($request, [
           'money'=>'required',
        ]);

        $user = $request->user();
        $money = $request->get("money");
        if($user->money < $money) {
            return Tx::fail("金额不足");
        }

        if (empty($user->alipay_account)){
            return Tx::fail("请完善提现信息");
        }
        $user->decrement('money',$money);

        $moneyRecord = MoneyRecord::create([
            'uid' => \Auth::id(),
            'money' => $money
                            ]);
        return Tx::success($moneyRecord,"操作成功，请等待打款");
    }
    //提现记录
    public function withdrawLog(){
        $log = MoneyRecord::where("uid",\Auth::id())->orderBy("id","desc")->limit(15)->get();
        return Tx::success($log);
    }

    public function updatePassword(Request $request)
    {
        $this->validate($request,
            [
                'old_password' => 'required',
                'password' => 'required',
            ]);

        if(md5($request->get("old_password")) != \Auth::user()->password){
            return Tx::fail("原密码错误");
        }

        User::where('id', \Auth::id())->update(['password'=>md5($request->get('password'))]);
        return  Tx::success('',"修改成功");
    }
}
